<template>
  <a-form :form="form">
    <a-form-item label="起运港" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <j-popup
        v-decorator="['pol', { rules: [{ required: true, message: '请选择起运港!' }] }]"
        :trigger-change="true"
        org-fields="wzm"
        dest-fields="pol"
        code="port_data"
        @callback="popupCallback" />
    </a-form-item>
    <a-form-item label="目的港" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <j-popup
        v-decorator="['pod', { rules: [{ required: true, message: '请选择目的港!' }] }]"
        :trigger-change="true"
        org-fields="wzm"
        dest-fields="pod"
        code="port_data"
        @callback="popupCallback" />
    </a-form-item>
    <a-form-item label="目的港还空箱时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <j-date placeholder="请选择目的港还空箱时间"
              :disabled-date="disabledDate"
              v-decorator="['podReturnboxTime', { rules: [{ required: true, message: '请选择目的港还空箱时间!' }] }]"
              @change="getReturnBoxDate"
              :trigger-change="true" style="width: 100%" />
    </a-form-item>
    <a-form-item label="目的港离场时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <j-date placeholder="请选择目的港离场时间"
              :disabled-date="disabledDate"
              v-decorator="['podLeaveTime', { rules: [{ required: true, message: '请选择目的港离场时间!' }] }]"
              :trigger-change="true" style="width: 100%"
              @change="getLevelDate"
      />
    </a-form-item>
    <a-form-item label="目的港堆场总费用" :labelCol="labelCol" :wrapperCol="wrapperCol"
    >
      <a-input
        :disabled=true
        v-decorator="['podYardTotalCost']"
      />
      <span>目的港堆场总费用=（目的港还空箱时间-目的港离场时间+1） x <a @click="handleShow">目的港堆场收费费率中的按天费用</a></span>
    </a-form-item>
    <a-form-item label="利润额" :labelCol="labelCol" :wrapperCol="wrapperCol"
                 help="利润额=卖箱费+用箱费-买箱费-目的港堆场总费用">
      <a-input
        :disabled=true
        v-decorator="['profit']"
      />
    </a-form-item>
    <a-form-item label="买箱费" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-input-number style="width: 100%"
                      @blur="calcProfit"
                      v-decorator="['buyBoxCost', validatorRules.buyBoxCost]"
      />
    </a-form-item>
    <a-form-item label="用箱费" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-input-number style="width: 100%"
                      @blur="calcProfit"
                      v-decorator="['useBoxCost', validatorRules.useBoxCost]"
      />
    </a-form-item>
    <a-form-item label="卖箱费" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-input-number style="width: 100%"
                      @blur="calcProfit"
                      v-decorator="['saleBoxCost', validatorRules.saleBoxCost]"
      />
    </a-form-item>
    <a-form-item label="目的港堆场信息" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 30px">
      <a-textarea
        v-decorator="['podYardInfo']"
        placeholder="请输入目的港堆场信息"
        :auto-size="{ minRows: 3, maxRows: 5 }"
      />
    </a-form-item>
    <a-modal
      title="目的港堆场收费费率中的按天费用"
      :visible="zvisible"
      :maskClosable="false"
      @ok="handleCancel1"
      @cancel="handleCancel1">
      <a-table
        :columns="columns"
        size="small"
        :pagination=false
        :data-source="data"
      />
    </a-modal>
  </a-form>

</template>

<script>

import JDate from '@/components/jeecg/JDate'
import moment from 'moment'
import { getAction, httpAction } from '@api/manage'
import { FormTypes } from '@/utils/JEditableTableUtil'

export default {
  name: 'ReturnBoxForm',
  components: {
    JDate
  },
  props: {
    // 数据源
    dataSource: {
      type: Object,
      required: true,
      default: () => {
      }
    }
  },

  data() {
    return {
      zvisible: false,
      leaveDate: '',
      returnBoxDate: '',
      form: this.$form.createForm(this, { name: 'horizontal_login' }),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      validatorRules: {
        buyBoxCost: {
          rules: [
            { required: true },
            { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ]
        },
        useBoxCost: {
          rules: [
            { required: true },
            { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ]
        },
        saleBoxCost: {
          rules: [
            { required: true },
            { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ]
        }
      },
      columns: [
        {
          title: '费用名称',
          dataIndex: 'costName',
          width: '100px'
        },
        {
          title: '计价单位',
          dataIndex: 'unit',
          width: '80px'
        },
        {
          title: '单价',
          dataIndex: 'price',
          width: '100px'
        },
        {
          title: '币种',
          dataIndex: 'currency',
          width: '60px'
        }
      ],
      data: [],
      daysCost: 0
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    moment,
    disabledDate(current) {
      return current && current > moment().endOf('day')
    },
    init() {
      console.log(this.dataSource)
      this.form.setFieldsValue(this.dataSource)
      let url = '/box.trade/jzxTrade/queryJzxDefaultCostDetailsByMainId'
      let params = { id: this.dataSource.id }
      getAction(url, params).then((res) => {
        let { result } = res
        let defaultCostDetail = []

        if (result) {
          if (Array.isArray(result)) {
            defaultCostDetail = result
          } else if (Array.isArray(result.records)) {
            defaultCostDetail = result.records
          }
        }
        let daysDatas = []
        let daysCost = 0
        defaultCostDetail.forEach(function(item, index) {
          if (item.unit === 'Day') {
            daysCost += parseFloat(item.price)
            daysDatas.push(item)
          }
        })
        this.data = daysDatas
        this.daysCost = daysCost
        console.log(this.data)
      }).finally(() => {
      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(row)
    },
    handleCancel1() {
      this.zvisible = false
    },
    handleShow() {
      this.zvisible = true
    },
    getLevelDate: function(v) {
      console.log(v)
      this.leaveDate = v
      if (this.returnBoxDate != '') {
        let diffDay = this.DateDiff(this.returnBoxDate, v)
        if (diffDay < 0) {
          this.returnBoxDate = ''
          this.$message.warning('还空箱时间不能早于离场时间')
          this.form.setFieldsValue({ 'podReturnboxTime': '' })
          this.form.setFieldsValue({ 'podLeaveTime': '' })
          this.form.setFieldsValue({ 'podYardTotalCost': 0 })
        } else {
          if (this.daysCost == 0) {
            this.form.setFieldsValue({ 'podYardTotalCost': 0 })
          } else {
            this.form.setFieldsValue({ 'podYardTotalCost': (diffDay + 1) * this.daysCost })
            this.calcProfit()
          }
        }
      }
    },
    getReturnBoxDate(v) {
      this.returnBoxDate = v
      if (this.leaveDate != '') {
        let diffDay = this.DateDiff(v, this.leaveDate)
        if (diffDay < 0) {
          this.leaveDate = ''
          this.$message.warning('还空箱时间不能早于离场时间')
          this.form.setFieldsValue({ 'podReturnboxTime': '' })
          this.form.setFieldsValue({ 'podLeaveTime': '' })
          this.form.setFieldsValue({ 'podYardTotalCost': 0 })
        } else {
          if (this.daysCost == 0) {
            this.form.setFieldsValue({ 'podYardTotalCost': 0 })
          } else {
            this.form.setFieldsValue({ 'podYardTotalCost': (diffDay + 1) * this.daysCost })
            this.calcProfit()
          }
        }
      }
    },
    calcProfit() {
      let userBoxCost = this.form.getFieldValue('useBoxCost')
      let buyBoxCost = this.form.getFieldValue('buyBoxCost')
      let saleBoxCost = this.form.getFieldValue('saleBoxCost')
      let podYardTotalCost = this.form.getFieldValue('podYardTotalCost')
      if (!podYardTotalCost) {
        podYardTotalCost = 0
      }
      let profit = saleBoxCost + userBoxCost - buyBoxCost - podYardTotalCost
      this.form.setFieldsValue({ 'profit': profit })
    },
    DateDiff(sDate1, sDate2) {    //sDate1和sDate2是2002-12-18格式
      let aDate, oDate1, oDate2, iDays
      aDate = sDate1.split('-')
      oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])    //转换为12-18-2002格式
      aDate = sDate2.split('-')
      oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
      iDays = parseInt((oDate1 - oDate2) / 1000 / 60 / 60 / 24)    //把相差的毫秒数转换为天数
      return iDays
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let url = '/box.trade/jzxTrade/returnbox', method = 'post'
          values['id']=this.dataSource.id
          httpAction(url, values, method).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
            } else {
              this.$message.warning(res.message)
            }
            this.$emit('cb', true)
          }).finally(() => {

          })
        } else {
          this.$emit('cb', false)
        }
      })
    }
  }

}
</script>

<style scoped>

</style>